package com.zmn.oms.services.impl.graborder;

import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.manager.utils.MongodbConsts;
import com.zmn.oms.model.mongo.graborder.GrabOrder;
import com.zmn.oms.services.interfaces.graborder.GrabOrderService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * 类描述：抢单
 *
 * @author liuying
 * @date 2021/07/13 11:17
 */
@Service
public class GrabOrderServiceImpl implements GrabOrderService {

    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private RedisManager redisManager;

    @Override
    public GrabOrder findGrabOrderByWorkId(Long workId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("workId").is(workId));
        return mongoTemplate.findOne(query, GrabOrder.class, MongodbConsts.OMS_GRAB_ORDER);
    }

    @Override
    public void updateGrabStatus(Long workId, Integer grabStatus, Integer masterId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("workId").is(workId));
        Update update = new Update();
        update.set("grabStatus", grabStatus);
        update.set("masterId", masterId);
        update.set("version", System.currentTimeMillis());
        mongoTemplate.updateFirst(query, update, GrabOrder.class, MongodbConsts.OMS_GRAB_ORDER);
    }

    @Override
    public void saveGrabOrder(GrabOrder grabOrder) {
        Objects.requireNonNull(grabOrder);
        Objects.requireNonNull(grabOrder.getWorkId());

        mongoTemplate.save(grabOrder, MongodbConsts.OMS_GRAB_ORDER);
    }

    @Override
    public void deleteGrabOrder(Long workId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("workId").is(workId));
        mongoTemplate.remove(query, GrabOrder.class, MongodbConsts.OMS_GRAB_ORDER);
        String redisKey = String.format(RedisKeyConsts.GRAB_CONSUME_ORDER_KEY, workId);
        redisManager.del(redisKey);
    }

    @Override
    public void deleteGrabOrderByDate(Date date) {
        Query query = new Query();
        query.addCriteria(Criteria.where("grabEndTime").lte(date));
        mongoTemplate.remove(query, GrabOrder.class, MongodbConsts.OMS_GRAB_ORDER);
    }

}
